package com.xgpro.mobile.studycentre.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xgpro.common.enums.ResultCodeEnum;
import com.xgpro.common.exceptions.BusinessRuntimeException;
import com.xgpro.common.service.BaseService;
import com.xgpro.common.utils.*;
import com.xgpro.domain.rolemanage.entity.Department;
import com.xgpro.domain.rolemanage.entity.Role;
import com.xgpro.domain.studycentre.entity.Course;
import com.xgpro.domain.studycentre.entity.CourseEVA;
import com.xgpro.domain.studycentre.entity.UserCourse;
import com.xgpro.domain.studycentre.vo.*;
import com.xgpro.domain.talentintroduction.dto.UserMessage;
import com.xgpro.domain.talentintroduction.entity.Attachment;
import com.xgpro.domain.talentintroduction.entity.User;
import com.xgpro.mapper.rolemanage.DepartmentMapper;
import com.xgpro.mapper.rolemanage.RoleMapper;
import com.xgpro.mapper.studycentre.AttachmentMapper;
import com.xgpro.mapper.studycentre.CourseEvaMapper;
import com.xgpro.mapper.studycentre.CourseMapper;
import com.xgpro.mapper.studycentre.UserCourseMapper;
import com.xgpro.mapper.talentintroduction.UserMapper;
import com.xgpro.mobile.studycentre.service.CourseService;
import com.xgpro.pc.rolemanage.service.UserService;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author tx
 * @version 1.0
 * @date 2019/8/25 12:09
 */
@Service
@Transactional(readOnly = false)
public class CourseServiceImpl extends BaseService implements CourseService{
    /**
     * 课程审批通过状态
     */
    private static final Integer PASS_COURSE_STATUS=1;

    /**
     * 课程审批新建状态
     */
    private static final Integer INIT_COURSE_STATUS=0;

    /**
     * 课程审批驳回状态
     */
    private static final Integer REF_COURSE_STATUS=2;
    /**
     * 课程公布状态
     */
    private static final Integer OPEN_FLAG=1;

    /**
     * 课程发布状态
     */
    private static final Integer IS_OPEN=1;

    /**
     * 课程发布初始
     */
    private static final Integer INIT_OPEN=0;

    /**
     * 课程教学状态
     */
    private static final Integer INIT_TEA_STATUS=0;

    /**
     * 参加课程人数
     */
    private static final Integer INIT_STUDENT_NUM=0;

    /**
     * 微课程类型
     */
    private static final Integer VIDEO_TYPE=2;

    /**
     * 课程类型
     */
    private static final Integer COURSE_NUM=2;


    /**
     * 已报名
     */
    private static final Integer SIGN_TURE=1;

    /**
     * 结课
     */
    private static final Integer OVER_STATUS=2;


    @Resource
    private CourseMapper courseMapper;

    @Resource
    private UserMapper userMapper;
    @Resource
    private SendMsgUtil sendMsgUtil;
    @Resource
    private UserCourseMapper userCourseMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private CourseEvaMapper courseEvaMapper;
    @Resource
    private DeptmentUtil deptmentUtil;
    @Resource
    private DDMsgUtil  ddMsgUtil;

    @Resource
    private UserService userService;
    /**
     *课程轮播图
     * @return
     */
    @Override
    public List<Course> qryCourseListForCarousel() {
        //轮播图条数
        Integer carouselSize = Integer.parseInt(ReadPropertiesUtil.readUrl("carousel_size"));
        Example example = new Example(Course.class);
        Example.Criteria criteria = example.createCriteria();
        //课程审批状态
        criteria.andEqualTo("status",PASS_COURSE_STATUS);
        //公开状态
        criteria.andEqualTo("flag",OPEN_FLAG);
        //发布状态
        criteria.andEqualTo("isOpen",IS_OPEN);
        //课程图片不为null
        criteria.andIsNotNull("photo");
        //课程状态类型 0内部课程面授 1外部课程 2微课程
        criteria.andNotEqualTo("courseType",VIDEO_TYPE);
        //课程开课时间比现在时间小
        criteria.andGreaterThanOrEqualTo("openTime",new Date());
        //排序
        example.setOrderByClause("update_time DESC");
        RowBounds rowBounds = new RowBounds(0, carouselSize);
        //选取最新的课程
        List<Course> courses = courseMapper.selectByExampleAndRowBounds(example, rowBounds);
        return courses;
    }


    /**
     * 添加课程信息
     * @param courseFront
     * @param userId
     * @return
     */
    @Override
    public Integer addCourse(CourseFront courseFront,Integer userId,Integer deptId) throws Exception {
        MultipartFile photoFile = courseFront.getPhotoFile();
        String photo=null;
        try {
            if(photoFile!=null){
                photo= FileTool.upLoad(photoFile, ReadPropertiesUtil.readUrl("course_photo"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Course course = new Course();
        course.setTitle(courseFront.getTitle());
        course.setSmallTitle(courseFront.getSmallTitle());
        String time=courseFront.getDate()+" "+courseFront.getTime();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        course.setOpenTime(df.parse(time));
        course.setAddress(course.getAddress());
        course.setIntroduce(course.getIntroduce());
        course.setStudents(course.getStudents());
        course.setStatus(INIT_COURSE_STATUS);
        course.setFlag(courseFront.getFlag());
        course.setNum(courseFront.getNum());
        course.setTeaStatus(INIT_TEA_STATUS);
        course.setIsOpen(INIT_OPEN);
        List<Integer> students = courseFront.getStudents();
        String studentStr="[]";
        Integer studentNum=0;
        if(students!=null&&students.size()>0){
            studentStr = JSONArray.toJSONString(students);
            studentNum= students.size();
        }
        course.setStudents(studentStr);
        course.setStudentNum(studentNum);
        course.setTeaId(userId);
        course.setTeaUsername(userMapper.selectByPrimaryKey(userId).getUsername());
        course.setDeptId(deptId);
        course.setIsOpen(INIT_OPEN);
        course.setCourseType(courseFront.getCourseType());
        course.setUpdateTime(new Date());
        course.setIntroduce(courseFront.getIntroduce());
        course.setAddress(courseFront.getAddress());
        course.setCourseDept(courseFront.getCourseDept());
        //上课时长
        course.setCourseTime(courseFront.getCourseTime());
        course.setPhoto(photo);
        int result = courseMapper.insertSelective(course);
        Integer id = course.getId();
        String text = ReadPropertiesUtil.readUrl("QRURL")+"?courseId="+id;
        String logoPath =ReadPropertiesUtil.readUrl("logoPath");
        String destPath = ReadPropertiesUtil.readUrl("destPath");
        try {
            String qr = QRCodeUtil.encode(text, logoPath, destPath, true);
            course.setQr(qr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        result=courseMapper.updateByPrimaryKeySelective(course);
        User user=userMapper.selectByPrimaryKey(userId);
        if(user!=null){
            Integer secondDeptId = user.getSecondDeptId();
            List<Integer> deptUserIds = courseMapper.selectDeptUserIds(secondDeptId, 2);
            if(deptUserIds!=null&&deptUserIds.size()>0){
                sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("remind_title"),ReadPropertiesUtil.readUrl("remind_content"),deptUserIds);
                String s = userService.selectAllUserId(deptUserIds);
                ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("remind_content"));
            }
        }

        return result;
    }

    /**
     * 根据审批状态进行区分
     * @param courseStatus
     * @return
     */
    @Override
    public List<CourseBack> qryCourseByStatusForApproval(CourseStatus courseStatus,Integer deptId,List<Integer> roleIds) {
        Integer flag=0;
        Integer count=0;
        for (Integer roleId : roleIds) {
            if(roleId.equals(1)){
                flag=1;
                count++;
            }
            if(roleId.equals(2)){
                flag=2;
                count++;
            }
        }
        Set<Integer> childDeptIds = deptmentUtil.getChildDeptIds(new HashSet<Integer>(), deptId);
        ArrayList<Integer> list = new ArrayList<>();
        for (Integer childDeptId : childDeptIds) {
            list.add(childDeptId);
        }
        Page<CourseBack> pages=null;
        long total=0;
        if(count==2){
            if(courseStatus.getStatus().equals(0)){
                PageHelper.startPage(courseStatus.getPage(),courseStatus.getPageSize());
                pages=(Page<CourseBack>)courseMapper.selectByStatusForCompany();
                total=pages.getTotal();
            }else{
                PageHelper.startPage(courseStatus.getPage(),courseStatus.getPageSize());
                pages=(Page<CourseBack>)courseMapper.selectByStatusForCom(courseStatus.getStatus());
                total=pages.getTotal();
            }
        }else{
            if(flag==1){
                if(courseStatus.getStatus().equals(0)){
                    PageHelper.startPage(courseStatus.getPage(),courseStatus.getPageSize());
                    pages=(Page<CourseBack>)courseMapper.selectByStatusForCom(3);
                    total=pages.getTotal();
                }else{
                    PageHelper.startPage(courseStatus.getPage(),courseStatus.getPageSize());
                    pages=(Page<CourseBack>)courseMapper.selectByStatusForCom(courseStatus.getStatus());
                    total=pages.getTotal();
                }
            }

            if(flag==2){
                PageHelper.startPage(courseStatus.getPage(),courseStatus.getPageSize());
                pages=(Page<CourseBack>)courseMapper.selectByStatus(courseStatus.getStatus(),list);
                total=pages.getTotal();
            }
        }
        List<CourseBack> result = pages.getResult().stream().filter(t->!(t.getStatus().equals(0)&&!list.contains(t.getDeptId()))).collect(Collectors.toList());
        if(result!=null&&result.size()>0){
            for (CourseBack courseBack : result) {
                courseBack.setTotals(total);
            }
        }
        return result;
    }

    /**
     * 通过课程id获取课程详情
     * @param id
     * @return
     */
    @Override
    public CourseInfo qryCourseInfoById(Integer id) {
        return courseMapper.selectCourseInfoById(id);
    }

    /**
     * 课程通过
     * @param id
     * @return
     */
    @Override
    public Integer passCourse(Integer id,List<Integer> roleIds) throws Exception {
        Example example = new Example(Course.class);
        example.createCriteria().andEqualTo("id",id);
        Course course = courseMapper.selectByPrimaryKey(id);
        Integer courseDept = course.getCourseDept();
        Integer status = course.getStatus();
        Integer result=0;
        for (Integer roleId : roleIds) {
            //角色里是部门管理员 并且状态是未审核，并且课程类型为部门级别
            if(roleId.equals(2)&&status.equals(0)&&courseDept.equals(0)){
                List<Integer> ids = new ArrayList<Integer>();
                ids.add(course.getTeaId());
                sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("course_app"),ReadPropertiesUtil.readUrl("course_success"),ids);
                String s = userService.selectAllUserId(ids);
                ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("course_success"));
                course.setStatus(PASS_COURSE_STATUS);
                return  courseMapper.updateByExampleSelective(course,example);
            }
            //角色里是部门管理员 并且状态是未审核，并且课程类型为公司课程
            if(roleId.equals(2)&&status.equals(0)&&courseDept.equals(1)){
                //留向公司管理员审批
                course.setStatus(3);
                List<Integer> companyUserIds = courseMapper.selectCompanyUserIds(1);
                    //提醒公司负责人审批
                sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("remind_title"),ReadPropertiesUtil.readUrl("remind_content"),companyUserIds);
                String s = userService.selectAllUserId(companyUserIds);
                ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("remind_content"));
                return courseMapper.updateByExampleSelective(course,example);
            }
            //角色里是公司理员 并且状态是未审核，并且课程类型为公司课程
            if(roleId.equals(1)&&status.equals(3)&&courseDept.equals(1)){
                List<Integer> ids = new ArrayList<Integer>();
                ids.add(course.getTeaId());
                sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("course_app"),ReadPropertiesUtil.readUrl("course_success"),ids);
                String s = userService.selectAllUserId(ids);
                ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("course_success"));
                course.setStatus(PASS_COURSE_STATUS);
                return  courseMapper.updateByExampleSelective(course,example);
            }
        }
            return result;
    }

    /**
     * 课程驳回
     * @param id
     * @param roleIds
     * @return
     */
    @Override
    public Integer refCourse(Integer id,List<Integer> roleIds) throws Exception {
        Example example = new Example(Course.class);
        example.createCriteria().andEqualTo("id",id);
        Course course = courseMapper.selectByPrimaryKey(id);
        Integer courseDept = course.getCourseDept();
        Integer status = course.getStatus();
        Integer result=0;
        for (Integer roleId : roleIds) {
            //角色里是部门管理员 并且状态是未审核，并且课程类型为部门级别
            if(roleId.equals(2)&&status.equals(0)){
                List<Integer> ids = new ArrayList<Integer>();
                ids.add(course.getTeaId());
                sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("course_app"),ReadPropertiesUtil.readUrl("course_fail"),ids);
                String s = userService.selectAllUserId(ids);
                ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("course_fail"));
                course.setStatus(REF_COURSE_STATUS);
                return  courseMapper.updateByExampleSelective(course,example);
            }
            //角色里是公司理员 并且状态是未审核，并且课程类型为公司课程
            if(roleId.equals(1)&&status.equals(3)&&courseDept.equals(1)){
                List<Integer> ids = new ArrayList<Integer>();
                ids.add(course.getTeaId());
                sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("course_app"),ReadPropertiesUtil.readUrl("course_fail"),ids);
                String s = userService.selectAllUserId(ids);
                ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("course_fail"));
                course.setStatus(REF_COURSE_STATUS);
                return  courseMapper.updateByExampleSelective(course,example);
            }
        }
        return result;
    }

    /**
     * 我的课程待讲
     * @param id
     * @return
     */
    @Override
    public List<CourseBack> openMyCourseList(Integer id,Integer isOpen) {
        List<CourseBack> list=new ArrayList<CourseBack>();
        if(isOpen!=null&&isOpen!=3){
            list=courseMapper.selectOpenList(id).stream().filter(t->t.getIsOpen().equals(isOpen)).collect(Collectors.toList());
        }else{
            list=courseMapper.selectOpenList(id);
        }
        return list;
    }

    /**
     * 发布课程通知
     * @param courseMessage
     */
    @Override
    public void openMyCourse(CourseMessage courseMessage) throws Exception {
        Integer courseId = courseMessage.getCourseId();
        String message = courseMessage.getMessage();
        Course course = courseMapper.selectByPrimaryKey(courseId);
        String students = course.getStudents();
        List<Integer> studentsList=null;
        if(!"[]".equals(students)){
            studentsList=(List<Integer>) JSONArray.parse(students);
            sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("course_confirm"),message,studentsList);
            String s = userService.selectAllUserId(studentsList);
            ddMsgUtil.sendMsg(s,message);
        }
        course.setIsOpen(OPEN_FLAG);
        Example example = new Example(Course.class);
        example.createCriteria().andEqualTo("id",courseId);
        //发布
        courseMapper.updateByExampleSelective(course,example);
        if(studentsList!=null){
            //添加t_user_course记录
            courseMapper.insertUserCourse(courseId,studentsList);
        }
    }


    /**
     * 我的课程申请中
     * @param id
     * @return
     */
    @Override
    public List<CourseBack> appMyCourseList(Integer id) {
        return courseMapper.selectAppList(id);
    }

    /**
     * 提醒审批
     * @param id
     */
    @Override
    public void remindApproval(Integer id) throws Exception {
        Course course = courseMapper.selectByPrimaryKey(id);
        if(course.getStatus()!=0&&course.getStatus()!=3){
            //不是待审批状态
            throw new BusinessRuntimeException(ResultCodeEnum.REMIND_FALE.getCode(),ResultCodeEnum.REMIND_FALE.getMessage());
        }
        List<Integer> deptUserIds=new ArrayList<Integer>();
        List<Integer> companyUserIds=new ArrayList<Integer>();
        Integer teaId = course.getTeaId();
        User user = userMapper.selectByPrimaryKey(teaId);
        Integer secondDeptId = user.getSecondDeptId();
        //role id=1代表公司负责人 2部门负责人
        Integer deptRoleId=2;
        Integer companyRoleId=1;
        deptUserIds = courseMapper.selectDeptUserIds(secondDeptId, deptRoleId);
        companyUserIds = courseMapper.selectCompanyUserIds(companyRoleId);
        if(course.getStatus()==0){
            //提醒部门负责人审批
            sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("remind_title"),ReadPropertiesUtil.readUrl("remind_content"),deptUserIds);
            String s = userService.selectAllUserId(deptUserIds);
            ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("remind_content"));
        }
        if(course.getStatus()==3){
            //提醒公司负责人审批
            sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("remind_title"),ReadPropertiesUtil.readUrl("remind_content"),companyUserIds);
            String s = userService.selectAllUserId(companyUserIds);
            ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("remind_content"));
        }
    }

    /**
     * 我的课程已讲
     * @param id
     * @return
     */
    @Override
    public List<CourseBack> achieveMyCourseList(Integer id) {
        return courseMapper.selectAchieveList(id);
    }

    /**
     * 报名课程
     * @return
     */
    @Override
    public List<CourseSignBack> qrySignCourse(CourseSignFront courseSignFront,Integer userId) {
//        CourseSignBackResult courseSignBackResult = new CourseSignBackResult();
        Example example = new Example(UserCourse.class);
        example.createCriteria().andEqualTo("studentId",userId);
        List<UserCourse> userCourses = userCourseMapper.selectByExample(example);
        List<Integer> ids=new ArrayList<Integer>();
        if(userCourses!=null&&userCourses.size()>0){
            for (UserCourse userCours : userCourses) {
                ids.add(userCours.getCourseId());
            }
        }
        Example example2 = new Example(Course.class);
        Example.Criteria criteria2 = example2.createCriteria();
        if(courseSignFront.getCourseType()!=null&&!"".equals(courseSignFront.getCourseType())){
            criteria2.andEqualTo("courseType",courseSignFront.getCourseType());
        }
        //课程审批状态
        criteria2.andEqualTo("status",PASS_COURSE_STATUS);
        //公开状态
        criteria2.andEqualTo("flag",OPEN_FLAG);
        //发布状态
        criteria2.andEqualTo("isOpen",IS_OPEN);
        //课程开课时间比现在时间小
        criteria2.andGreaterThanOrEqualTo("openTime",new Date());
        //结课为未结课
        criteria2.andEqualTo("teaStatus",0);
        if(courseSignFront.getCourseName()!=null&&!"".equals(courseSignFront.getCourseName())){
            //课程名称模糊搜索
            criteria2.andLike("title","%"+courseSignFront.getCourseName()+"%");
        }
        if(courseSignFront.getTeaName()!=null&&!"".equals(courseSignFront.getTeaName())){
            //导师名称模糊查询
            criteria2.andLike("teaUsername","%"+courseSignFront.getTeaName()+"%");
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(courseSignFront.getStartTime()!=null&&!"".equals(courseSignFront.getStartTime())){
            try {
                Date startTime = dateFormat.parse(courseSignFront.getStartTime());
                criteria2.andGreaterThanOrEqualTo("openTime",startTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if(courseSignFront.getEndTime()!=null&&!"".equals(courseSignFront.getEndTime())){
            try {
                Date endTime = dateFormat.parse(courseSignFront.getEndTime());
                criteria2.andLessThanOrEqualTo("openTime",endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //排序
        example2.setOrderByClause("update_time DESC");
        PageHelper.startPage(courseSignFront.getPage(),courseSignFront.getPageSize());
        Page<Course> pages=(Page<Course>)courseMapper.selectByExample(example2);
        long total = pages.getTotal();
        List<Course> result = pages.getResult();
        List<Integer> courseIds=new ArrayList<Integer>();
        for (Course course : result) {
            courseIds.add(course.getId());
        }
        List<CourseSignBack> courseSignBacks=new ArrayList<CourseSignBack>();
        if(courseIds!=null&&courseIds.size()>0){
            courseSignBacks = courseMapper.selectCourseSignBackList(courseIds);
            for (CourseSignBack courseSignBack : courseSignBacks) {
                courseSignBack.setTotals(total);
                for (Integer id : ids) {
                    if(courseSignBack.getId().equals(id)){
                        courseSignBack.setIsSign(SIGN_TURE);
                    }
                }
            }
        }
        List<CourseSignBack> smallCourseList = courseSignBacks.stream().filter(x -> x.getCourseType() == 2&&x.getAnnxId() != null && !"".equals(x.getAnnxId())).collect(Collectors.toList());
        if(smallCourseList!=null&&smallCourseList.size()>0){
            List<Integer> annxIdList = smallCourseList.stream().map(x -> x.getAnnxId()).collect(Collectors.toList());
            example=new Example(Attachment.class);
            example.createCriteria().andIn("id",annxIdList);
            List<Attachment> attachments = attachmentMapper.selectByExample(example);
            for (CourseSignBack courseSignBack : courseSignBacks) {
                for (Attachment attachment : attachments) {
                    if(attachment.getId().equals(courseSignBack.getAnnxId())){
                        courseSignBack.setFileType(attachment.getFileType());
                    }
                }
            }
        }
        return courseSignBacks;
    }

    /**
     * 报名课程
     * @param userId
     * @param courseId
     * @return
     */
    @Override
    public Integer signOneCourse(Integer userId, Integer courseId) {
        synchronized(this){
            Example example1 = new Example(UserCourse.class);
            Example.Criteria criteria = example1.createCriteria();
            criteria.andEqualTo("studentId",userId);
            criteria.andEqualTo("courseId",courseId);
            List<UserCourse> userCourses = userCourseMapper.selectByExample(example1);
            if(userCourses.size()>0){
                //防止重复报名
                throw new BusinessRuntimeException(ResultCodeEnum.HAD_SIGN.getCode(),ResultCodeEnum.HAD_SIGN.getMessage());
            }
            Course course = courseMapper.selectByPrimaryKey(courseId);
            Integer studentNum = course.getStudentNum();
            if(studentNum+1>course.getNum()){
                throw new BusinessRuntimeException(ResultCodeEnum.FULL_STUDENT.getCode(),ResultCodeEnum.FULL_STUDENT.getMessage());
            }
            Integer result = userCourseMapper.insertSignMessage(userId, courseId);
            course.setStudentNum(course.getStudentNum()+1);
            Example example = new Example(Course.class);
            example.createCriteria().andEqualTo("id",courseId);
            result=courseMapper.updateByExampleSelective(course,example);
            return result;
        }
    }

    /**
     * 参加的课程
     * @param mySignCourseFront
     * @param userId
     * @return
     */
    @Override
    public List<MySignCourseBack> qryMySignCourse(MySignCourseFront mySignCourseFront,Integer userId) {
        Integer courseType = mySignCourseFront.getCourseType();
        Integer status = mySignCourseFront.getStatus();
        Example example = new Example(UserCourse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",status);
        criteria.andEqualTo("studentId",userId);
        List<UserCourse> userCourses = userCourseMapper.selectByExample(example);
        List<Integer> courseIds=new ArrayList<Integer>();
        if(userCourses!=null&&userCourses.size()>0){
            for (UserCourse userCours : userCourses) {
                courseIds.add(userCours.getCourseId());
            }
        }
        List<MySignCourseBack> mySignCourseBacks=new ArrayList<MySignCourseBack>();
        if(courseIds!=null&&courseIds.size()>0){
             long total=0;
             if(courseType==null||"".equals(courseType)){
                 PageHelper.startPage(mySignCourseFront.getPage(),mySignCourseFront.getPageSize());
                 Page<MySignCourseBack> pages=(Page<MySignCourseBack>)courseMapper.qrySignCourse(courseIds);
                 total=pages.getTotal();
                 mySignCourseBacks = pages.getResult();
                 if(mySignCourseBacks!=null&&mySignCourseBacks.size()>0){
                     List<MySignCourseBack>  result = mySignCourseBacks.stream().filter(x -> x.getAnnxId() != null && !"".equals(x.getAnnxId())).collect(Collectors.toList());
                     List<Integer> annxIds = result.stream().map(x -> x.getAnnxId()).collect(Collectors.toList());
                     if(annxIds!=null&&annxIds.size()>0){
                         example=new Example(Attachment.class);
                         example.createCriteria().andIn("id",annxIds);
                         List<Attachment> attachments = attachmentMapper.selectByExample(example);
                         for (MySignCourseBack mySignCourseBack : mySignCourseBacks) {
                             for (Attachment attachment : attachments) {
                                 if(attachment.getId().equals(mySignCourseBack.getAnnxId())){
                                     mySignCourseBack.setFileType(attachment.getFileType());
                                 }
                             }
                         }
                     }
                 }

             }else{
                 PageHelper.startPage(mySignCourseFront.getPage(),mySignCourseFront.getPageSize());
                 Page<MySignCourseBack> pages=(Page<MySignCourseBack>)courseMapper.qrySignCourseByCourseType(courseIds,courseType);
                 total=pages.getTotal();
                 mySignCourseBacks = pages.getResult();
                 if(mySignCourseBacks!=null&&mySignCourseBacks.size()>0){
                     List<MySignCourseBack>  result = mySignCourseBacks.stream().filter(x -> x.getAnnxId() != null && !"".equals(x.getAnnxId())).collect(Collectors.toList());
                     List<Integer> annxIds = result.stream().map(x -> x.getAnnxId()).collect(Collectors.toList());
                     if(annxIds!=null&&annxIds.size()>0) {
                         example = new Example(Attachment.class);
                         example.createCriteria().andIn("id", annxIds);
                         List<Attachment> attachments = attachmentMapper.selectByExample(example);
                         for (MySignCourseBack mySignCourseBack : mySignCourseBacks) {
                             for (Attachment attachment : attachments) {
                                 if (attachment.getId().equals(mySignCourseBack.getAnnxId())) {
                                     mySignCourseBack.setFileType(attachment.getFileType());
                                 }
                             }
                         }
                     }
                 }
             }
            for (MySignCourseBack mySignCourseBack : mySignCourseBacks) {
                mySignCourseBack.setTotals(total);  
                for(UserCourse usercourse :userCourses) {
                	 if(mySignCourseBack.getId().equals(usercourse.getCourseId())){
                		 mySignCourseBack.setIsEva(usercourse.getIsEva());
                	 }
                }
            }
        }
        return mySignCourseBacks;
    }

    /**
     * 课程中心列表
     * @param courseCentreFront
     * @return
     */
    @Override
    public CourseCentreBackResult qryCourseCentre(CourseCentreFront courseCentreFront) {
        CourseCentreBackResult courseCentreBackResult = new CourseCentreBackResult();
        Integer courseType = courseCentreFront.getCourseType();
        Example example = new Example(Course.class);
        Example.Criteria criteria = example.createCriteria();
        if(courseType==null||"".equals(courseType)){
            ArrayList<Integer> courseTypes = new ArrayList<>();
            courseTypes.add(0);
            courseTypes.add(1);
            criteria.andIn("courseType",courseTypes);
        }else{
            if(courseType==0){
                //面授内部课程
                criteria.andEqualTo("courseType",0);
            }
            if(courseType==1){
                //面授外部课程
                criteria.andEqualTo("courseType",1);
            }
            if(VIDEO_TYPE.equals(courseType)){
                //微课程
                criteria.andEqualTo("courseType",VIDEO_TYPE);
                if(courseCentreFront.getCourseType()!=null){
                    criteria.andEqualTo("smallType",courseCentreFront.getSmallType());
                }

            }
        }
        //课程审批状态
        criteria.andEqualTo("status",PASS_COURSE_STATUS);
        //公开状态
        criteria.andEqualTo("flag",OPEN_FLAG);
        //发布状态
        criteria.andEqualTo("isOpen",IS_OPEN);
        //课程开课时间比现在时间小
        //criteria.andGreaterThanOrEqualTo("openTime",new Date());
        //排序
        example.setOrderByClause("update_time DESC");
        PageHelper.startPage(courseCentreFront.getPage(),courseCentreFront.getPageSize());
        Page<Course> pages=(Page<Course>)courseMapper.selectByExample(example);
        long total = pages.getTotal();
        courseCentreBackResult.setTotals(total);
        List<Course> courses = pages.getResult();
        List<Integer> userIds=new ArrayList<Integer>();
        List<CourseCentreBack> courseCentreBacks = new ArrayList<>();
        CourseCentreBack courseCentreBack = null;
        if(courses!=null&&courses.size()>0&&!VIDEO_TYPE.equals(courseType)){
            for (Course cours : courses) {
                 userIds.add(cours.getTeaId());
            }
            List<UserMessage> userMessages = userMapper.selectByList(userIds);
            for (Course cours : courses) {
                courseCentreBack=new CourseCentreBack();
                courseCentreBack.setId(cours.getId());
                courseCentreBack.setCoursePhoto(cours.getPhoto());
                courseCentreBack.setTitle(cours.getTitle());
                courseCentreBack.setTotals(total);
                courseCentreBack.setOpenTime(cours.getOpenTime());
                if(userMessages!=null&&userMessages.size()>0){
                    for (UserMessage userMessage : userMessages) {
                         if(userMessage.getId().equals(cours.getTeaId())){
                             courseCentreBack.setUserId(userMessage.getId());
                             courseCentreBack.setUserName(userMessage.getUsername());
                             courseCentreBack.setDeptName(userMessage.getDeptname());
                             courseCentreBack.setPhoto(userMessage.getPhoto());
                         }
                    }
                }
                courseCentreBacks.add(courseCentreBack);
            }
        }
        if(courses!=null&&courses.size()>0&&VIDEO_TYPE.equals(courseType)){
            List<Integer> annixIds = courses.stream().map(x -> x.getAnnxId()).collect(Collectors.toList());
            Example example1 = new Example(Attachment.class);
            Example.Criteria criteria1 = example1.createCriteria();
            criteria1.andIn("id",annixIds);
            List<Attachment> attachments = attachmentMapper.selectByExample(example1);
            //微课程
            for (Course cours : courses) {
                for (Attachment attachment : attachments) {
                    if(attachment.getId().equals(cours.getAnnxId())){
                        courseCentreBack=new CourseCentreBack();
                        courseCentreBack.setId(cours.getId());
                        courseCentreBack.setCoursePhoto(cours.getPhoto());
                        courseCentreBack.setTitle(cours.getTitle());
                        courseCentreBack.setTotals(total);
                        courseCentreBack.setFileType(attachment.getFileType());
                        courseCentreBacks.add(courseCentreBack);
                    }
                }
            }
        }
        courseCentreBackResult.setCourseCentreBacks(courseCentreBacks);
        return courseCentreBackResult;
    }


    /**
     * 查询教师详细信息
     * @param id
     * @return
     */
    @Override
    public TeacherBack qryTeacherByUserId(Integer id) {
        TeacherBack teacherBack = userMapper.selectTeacherByUserId(id);
        return teacherBack;
    }

    /**
     * 根据课程状态查询自己的课程
     * @param myCourse
     * @return
     */
    /*@Override
    public List<Course> qryMyCourse(Integer userId,MyCourse myCourse) {
        PageHelper.startPage(myCourse.getPage(),myCourse.getPageSize());
        Example example = new Example(Course.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",myCourse.getStatus());
        if(userId==null){
            throw new BusinessRuntimeException(ResultCodeEnum.NO_SESSION.getCode(),ResultCodeEnum.NO_SESSION.getMessage());
        }
        criteria.andEqualTo("teaId",userId);
        List<Course> courses=null;
        if(myCourse.getStatus()==0){
             Page<Course> pages =(Page<Course>) courseMapper.selectByExample(example);
             courses = pages.getResult();

        }else{
             //teaStatus 0,代表待讲 1,代表已将
             criteria.andEqualTo("teaStatus",myCourse.getTeaStatus());
             Page<Course> pages =(Page<Course>) courseMapper.selectByExample(example);
             courses = pages.getResult();
        }
        return courses;
    }*/

    /**
     * 结课
     * @param overCourseFront
     * @return
     */
    @Override
    public Integer overStudy(OverCourseFront overCourseFront) throws Exception {
        //List<MultipartFile> photoFiles = overCourseFront.getPhotoFiles();
        //List<String> photoList = new ArrayList<>();
        //for (MultipartFile photoFile : photoFiles) {
          //  String photo=FileTool.upLoad(photoFile,ReadPropertiesUtil.readUrl("course_photo"));
           // photoList.add(photo);
        //}
        //String filePath=FileTool.upLoad(overCourseFront.getFile(),"course_photo");
        //String photoStr="[]";
        //if(photoList.size()>0){
          //  photoStr=JSONArray.toJSONString(photoList);
        //}
        Course course = new Course();
        //course.setStudyPhotos(photoStr);
        //course.setStudyFile(filePath);
        course.setTeaStatus(OVER_STATUS);
        List<Integer> ids = userMapper.selectListByRoleId();
        sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("course_over"),ReadPropertiesUtil.readUrl("course_finish"),ids);
        String s = userService.selectAllUserId(ids);
        ddMsgUtil.sendMsg(s,ReadPropertiesUtil.readUrl("course_finish"));
        Example exam=new Example(UserCourse.class);
        exam.createCriteria().andEqualTo("courseId",overCourseFront.getCourseId());
        List<UserCourse> userCourses = userCourseMapper.selectByExample(exam);
        if(userCourses!=null&&userCourses.size()>0){
            List<Integer> userIds = userCourses.stream().map(x -> x.getStudentId()).collect(Collectors.toList());
            sendMsgUtil.sendMsg(COURSE_NUM,ReadPropertiesUtil.readUrl("over_title"),ReadPropertiesUtil.readUrl("over_content"),userIds);
            String sss = userService.selectAllUserId(userIds);
            ddMsgUtil.sendMsg(sss,ReadPropertiesUtil.readUrl("over_content"));
        }
        Example example = new Example(Course.class);
        example.createCriteria().andEqualTo("id",overCourseFront.getCourseId());
        return courseMapper.updateByExampleSelective(course,example);
    }

    @Override
    public List<Department> qryDeptMessage(String id ) {
        Example example = new Example(Department.class);
        Example.Criteria criteria = example.createCriteria();
        if (!id.isEmpty()){
            example.createCriteria().andEqualTo("id",id);
        }

        List<Department> departments = new ArrayList<>();
//        if (userName.isEmpty()){
            if (id.isEmpty()){
                criteria.andNotEqualTo("ddId",1);
                criteria.andNotEqualTo("pid",1);

//                departments = departmentMapper.selectAll();
                departments = departmentMapper.selectByExample(example);
            }else {
                Department department = departmentMapper.selectByPrimaryKey(id);
                departments.add(department);
            }
//        }else {
//            Example example1 = new Example(User.class);
//            example1.createCriteria().andLike("username",userName);
//            List<User> users = userMapper.selectByExample(example1);
//            for (User user : users) {
//                Department department = departmentMapper.selectByPrimaryKey(user.getDeptId());
//                departments.add(department);
//            }
//        }

        return departments;
    }

    @Override
    public List<Department> qryCourseDeptMessage(String id, String userName) {
        Example example = new Example(Department.class);
        Example.Criteria criteria1 = example.createCriteria();
        if (!id.isEmpty()){
            criteria1.andEqualTo("id",id);
        }

        List<Department> departments = new ArrayList<>();
        if (userName.isEmpty()){
        if (id.isEmpty()){
            criteria1.andNotEqualTo("ddId",1);
            criteria1.andNotEqualTo("pid",1);
            departments = departmentMapper.selectByExample(example);
        }else {
            Department department = departmentMapper.selectByPrimaryKey(id);
            departments.add(department);
        }
        }else {
            Example example1 = new Example(User.class);
            Example.Criteria criteria = example1.createCriteria();

            criteria.andLike("username","%"+ userName+"%");
            criteria.andIsNotNull("deptId");
            List<User> users = userMapper.selectByExample(example1);
            for (User user : users) {
                Department department = departmentMapper.selectByPrimaryKey(user.getDeptId());
                if (departments.contains(department)){
                    continue;
                }
                departments.add(department);
            }
        }

        return departments;
    }

    /**
     * 查询部门及部门所属人员信息(搜索)
     * @param id
     * @param userName
     * @return
     */
    @Override
    public List<User> qryCourseDeptUserList(String id, String userName) {
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        if (!id.isEmpty()){
            criteria.andEqualTo("deptId",id);
        }
        List<User> users = new ArrayList<>();
//        example.createCriteria().andEqualTo("deptId",id);
        if(userName.isEmpty()){
            users = userMapper.selectByExample(example);
        } else {
            criteria.andLike("username","%"+ userName+"%");
            users = userMapper.selectByExample(example);
        }
        return users;
    }

    /**
     * 查询部门及部门所属人员信息
     * @param id)
     * @return
     */
    @Override
    public List<User> qryDeptUserList(String id ) {
        Example example = new Example(Course.class);
//        List<User> users = new ArrayList<>();
        example.createCriteria().andEqualTo("deptId",id);
//        if(userName.isEmpty()){
        List<User> users = userMapper.selectByExample(example);
//        } else {
//            example.createCriteria().andLike("username",userName);
//            users = userMapper.selectByExample(example);
//        }
        return users;
    }

    /**
     * 课程评估
     * @param map
     * @param userId
     * @return
     */
    @Override
    public Integer courseEva(Map map,Integer userId) {
        Integer courseId =(Integer) map.get("courseId");
        Example example = new Example(UserCourse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("courseId",courseId);
        criteria.andEqualTo("studentId",userId);
        List<UserCourse> userCourses = userCourseMapper.selectByExample(example);
        UserCourse userCourse=null;
        if(userCourses!=null&&userCourses.size()>0){
            userCourse=userCourses.get(0);
        }else{
            throw new BusinessRuntimeException(ResultCodeEnum.COURSE_FAILE_01.getCode(),ResultCodeEnum.COURSE_FAILE_01.getMessage());
        }
        if(userCourse.getIsEva().equals(1)){
            throw new BusinessRuntimeException(ResultCodeEnum.COURSE_FAILE_02.getCode(),ResultCodeEnum.COURSE_FAILE_02.getMessage());
        }
        if(userCourse.getStatus().equals(0)){
            throw new BusinessRuntimeException(ResultCodeEnum.COURSE_FAILE_03.getCode(),ResultCodeEnum.COURSE_FAILE_03.getMessage());
        }
        User user = userMapper.selectByPrimaryKey(userId);
        String stuName = user.getUsername();
        Course course = courseMapper.selectByPrimaryKey(courseId);
        if(course==null){
            throw new BusinessRuntimeException(ResultCodeEnum.COURSE_FAILE_04.getCode(),ResultCodeEnum.COURSE_FAILE_04.getMessage());
        }
        String teaName=course.getTeaUsername();
        String title=course.getTitle();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String courseTime=sf.format(course.getOpenTime());
        String excleName=user.getUsername()+"课程评价"+System.currentTimeMillis();
        String temUrl=ReadPropertiesUtil.readUrl("coureTemUrl");
        Map<String, String> excelMap = new HashMap<String, String>();
        excelMap.put("temUrl",temUrl);
        excelMap.put("excleName",excleName);
        excelMap.put("teaName","讲师姓名:"+teaName);
        excelMap.put("title","课程名称："+title);
        excelMap.put("stuName","评价人："+stuName);
        excelMap.put("courseTime","培训时间: "+courseTime);
        excelMap.put("row1",(Integer)map.get("row1")+"星");
        excelMap.put("row2",mappingStr((Integer)map.get("row2")));
        excelMap.put("row3",mappingStr((Integer)map.get("row3")));
        excelMap.put("row4",mappingStr((Integer)map.get("row4")));
        excelMap.put("row5",mappingStr((Integer)map.get("row5")));
        excelMap.put("row6",mappingStr((Integer)map.get("row6")));
        excelMap.put("row7",mappingStr((Integer)map.get("row7")));
        excelMap.put("row8",mappingStr((Integer)map.get("row8")));
        excelMap.put("row9",mappingStr((Integer)map.get("row9")));
        excelMap.put("row10",mappingStr((Integer)map.get("row10")));
        excelMap.put("row11",(String) map.get("row11"));
        excelMap.put("row12",(String) map.get("row12"));
        String filePath="";
        try {
            filePath = ExcelExporeUtil.createExcle(excelMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CourseEVA courseEVA = new CourseEVA();
        courseEVA.setRow1((Integer)map.get("row1"));
        courseEVA.setRow2((Integer)map.get("row2"));
        courseEVA.setRow3((Integer)map.get("row3"));
        courseEVA.setRow4((Integer)map.get("row4"));
        courseEVA.setRow5((Integer)map.get("row5"));
        courseEVA.setRow6((Integer)map.get("row6"));
        courseEVA.setRow7((Integer)map.get("row7"));
        courseEVA.setRow8((Integer)map.get("row8"));
        courseEVA.setRow9((Integer)map.get("row9"));
        courseEVA.setRow10((Integer)map.get("row10"));
        courseEVA.setRow11((String) map.get("row11"));
        courseEVA.setRow12((String) map.get("row12"));
        courseEvaMapper.insertSelective(courseEVA);
        Integer evaId = courseEVA.getId();
        userCourse.setIsEva(1);
        userCourse.setEvaTime(new Date());
        userCourse.setEvaId(evaId);
        userCourse.setUrl(filePath);
        return userCourseMapper.updateByPrimaryKeySelective(userCourse);
    }




    /**
     * 映射字符串
     * @param num
     * @return
     */
    private String mappingStr(Integer num){
            String evaStr="";
            switch (num){
                case 1:
                    evaStr="完全同意";
                    break;
                case 2:
                    evaStr="同意";
                    break;
                case 3:
                    evaStr="一般";
                    break;
                case 4:
                    evaStr="不同意";
                    break;
                case 5:
                    evaStr="完全不同意";
                    break;
                default:
                    break;
            }
            return evaStr;
    }


    @Resource
    private AttachmentMapper attachmentMapper;

    /**
     * 微课程播放
     * @return
     */
    @Override
    public SmallCourseInfo qrySmallCourseInfo(Integer id,Integer userId) {
        Course course = courseMapper.selectByPrimaryKey(id);
        if(course==null){
            throw new BusinessRuntimeException(ResultCodeEnum.COURSE_FAILE_04.getCode(),ResultCodeEnum.COURSE_FAILE_04.getMessage());
        }
        Integer annxId = course.getAnnxId();
        Attachment attachment = attachmentMapper.selectByPrimaryKey(annxId);
        SmallCourseInfo smallCourseInfo = new SmallCourseInfo();
        smallCourseInfo.setId(course.getId());
        smallCourseInfo.setTitle(course.getTitle());
        smallCourseInfo.setIntroduce(course.getIntroduce());
        smallCourseInfo.setFilePath(attachment.getFilePath());
        smallCourseInfo.setFileType(attachment.getFileType());
        smallCourseInfo.setPhoto(course.getPhoto());
        smallCourseInfo.setSmallType(course.getSmallType());
        Example example = new Example(UserCourse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("courseId",id);
        criteria.andEqualTo("studentId",userId);
        List<UserCourse> userCourses = userCourseMapper.selectByExample(example);
        if(userCourses==null||userCourses.size()==0){
            UserCourse userCourse = new UserCourse();
            userCourse.setStudentId(userId);
            userCourse.setCourseId(id);
            userCourse.setStatus(1);
            userCourseMapper.insertSelective(userCourse);
        }
        return smallCourseInfo;
    }

    /**
     * 查询外部导师人员信息
     * @param name
     * @return
     */
    @Override
    public List<User> qryOutUserList(String name) {
        List<User> list = userMapper.selectOutTeacher(name);
        return list;
    }

    /**
     * 扫码
     * @param courseId
     * @param userId
     * @return
     */
    @Override
    public String doQR(Integer courseId, Integer userId) {
        Example example = new Example(UserCourse.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("studentId",userId);
        criteria.andEqualTo("courseId",courseId);
        List<UserCourse> userCourses = userCourseMapper.selectByExample(example);
        if(userCourses!=null&&userCourses.size()>0){
            Integer status = userCourses.get(0).getStatus();
            if(status==0){
                UserCourse userCourse = userCourses.get(0);
                userCourse.setStatus(1);
                int result = userCourseMapper.updateByPrimaryKeySelective(userCourse);
                if(result==1){
                    System.out.println("签到成功");
                    return "签到成功";
                }
                System.out.println("签到失败");
                return "签到失败";
            }else{
                System.out.println("您已签过到");
                return "您已签过到";
            }
        }else{
            System.out.println("您未参与该课程");
            return "您未参与该课程";
        }
    }

    /**
     * 首页精品课程
     * @return
     */
    @Override
    public GoodCourseResult getGoodCourses() {
        GoodCourseResult goodCourseResult = new GoodCourseResult();
        Example example = new Example(Course.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isGood",1);
        criteria.andEqualTo("courseType",0);
        example.setOrderByClause("update_time DESC");
        List<Course> courses = courseMapper.selectByExample(example);
        if(courses!=null&&courses.size()>0){
           List<Integer> teaIds = new ArrayList<>();
            for (Course cours : courses) {
                Integer teaId = cours.getTeaId();
                teaIds.add(teaId);
            }
            List<UserMessage> userMessages = userMapper.selectByList(teaIds);
            GoodCourses goodCourses=null;
            ArrayList<GoodCourses> goodCoursesArrayList = new ArrayList<>();
            int count=0;
            for (Course cours : courses) {
                for (UserMessage userMessage : userMessages) {
                    if(cours.getTeaId().equals(userMessage.getId())){
                        goodCourses = new GoodCourses();
                        goodCourses.setId(cours.getId());
                        goodCourses.setCoursePhoto(cours.getPhoto());
                        goodCourses.setTitle(cours.getTitle());
                        goodCourses.setPhoto(userMessage.getPhoto());
                        goodCourses.setUsername(userMessage.getUsername());
                        goodCourses.setDeptName(userMessage.getDeptname());
                        goodCoursesArrayList.add(goodCourses);
                        count++;
                    }
                }
            }
            goodCourseResult.setGoodCourseList(goodCoursesArrayList);
            goodCourseResult.setTotals(count);
        }
        return goodCourseResult;
    }

    @Override
    public List<Department> qryLikeDeptMessage(String name) {

        Example example = new Example(Department.class);
        if (!name.isEmpty()){
            example.createCriteria().andLike("name","%"+name+"%");
        }


        List<Department> departments  = departmentMapper.selectByExample(example);
        return departments;
    }

}
